package com.example.monitor.service.impl;

import com.example.monitor.model.DTO.UserTrendQueryDTO;
import com.example.monitor.model.VO.ResultVO;
import com.example.monitor.model.VO.UserTrendVO;
import com.example.monitor.repository.AlarmRecordRepository;
import com.example.monitor.service.UserTrendService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserTrendServiceImpl implements UserTrendService {

    private final AlarmRecordRepository alarmRecordRepository;

    @Override
    public ResultVO<UserTrendVO> getUserTrend(UserTrendQueryDTO queryDTO) {
        // 初始化12个月的数据为0
        int[] monthlyCounts = new int[12];

        // 查询数据库获取实际数据
        List<Object[]> rawData = alarmRecordRepository.countMonthlyByWorker(
                queryDTO.getWorkerId(),
                queryDTO.getYear());

        // 填充查询结果
        rawData.forEach(arr -> {
            int month = ((Number) arr[0]).intValue() - 1; // 转换为0-based索引
            int count = ((Number) arr[1]).intValue();
            monthlyCounts[month] = count;
        });

        // 构建返回对象
        UserTrendVO result = new UserTrendVO();
        result.setCategories(Arrays.asList("1月", "2月", "3月", "4月", "5月", "6月",
                "7月", "8月", "9月", "10月", "11月", "12月"));
        result.setSeries(Arrays.stream(monthlyCounts).boxed().collect(Collectors.toList()));

        return ResultVO.success("查询成功", result);
    }
}
